<?php
class Google_API_translator {
	public $url = "http://translate.google.com/translate_t";
	public $text = ""; //翻译文本   
	public $out = ""; //翻译输出 
	public $lang_src = ""; //要翻译的语言
	public $lang_des = ""; //翻译成的语言

	function setText($text) {
		$this->text = $text;
	}

	function setLang($lang_src, $lang_des) {
		$this->lang_src = $lang_src;
		$this->lang_des = $lang_des;
	}

	function translate() {
		$this->out = "";
		$this->out = $this->postPage($this->url, $this->text, $this->lang_src, $this->lang_des);
		return $this->out;
	}

	function postPage($url, $text, $lang_src, $lang_des) {
		$html = '';

		if ($url != "" && $text != "" && $lang_src != "" && $lang_des != "") {

			//伪造header   
			$ch = curl_init($url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_HEADER, 1);
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
			curl_setopt($ch, CURLOPT_TIMEOUT, 15);
			$header = array (
				'Accept-Language: zh-cn',
				'Connection: Keep-Alive',
				'Cache-Control: no-cache'
			);
			curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
			$useragent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)";
			curl_setopt($ch, CURLOPT_USERAGENT, $useragent);

			$fields = array (
				'prev=_t',
				'eotf=1',
				'layout=2',
				'js=n',
				'hl=zh-CN',
				'sl=' . $lang_src,
				'tl=' . $lang_des,
				'ie=UTF-8',
				'text=' . urlencode($text)
			);
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, implode('&', $fields));

			$html = curl_exec($ch);
			if (curl_errno($ch))
				$html = "";
			curl_close($ch);
		}
		return $html;
	}
}

//翻译调用接口

function google_trans($text_in, $lang_in, $lang_out) {
	//翻译
	@header("content-type:text/html;charset=utf-8");
	$trans = new Google_API_translator();
	$trans->setLang($lang_in, $lang_out);
	$trans_str = $text_in;
	$trans->setText($trans_str);
	//输出处理	
	require(dirname(__FILE__) . '/simple_html_dom.php');
	$html = new simple_html_dom;
	$html->load($trans->translate());
	$text_out = $html->find('#result_box', 0)->innertext();
	$text_out = preg_replace("/title=\"(.*)\" onmouseover=\"this.style.backgroundColor='#ebeff9'\" onmouseout=\"this.style.backgroundColor='#fff'\"/isU", '', $text_out);
	return $text_out;
}
?>
